package com.cardvalue.sys.activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.cardvalue.sys.R;
import com.cardvalue.sys.base.BaseActivity;
import com.cardvalue.sys.cache.LocalCache;
import com.cardvalue.sys.entity.Apply;
import com.cardvalue.sys.entity.CheckMobileRegisterAuth;
import com.cardvalue.sys.entity.Credit;
import com.cardvalue.sys.entity.Login;
import com.cardvalue.sys.entity.Message;
import com.cardvalue.sys.entity.User;
import com.cardvalue.sys.mode.LoginService;
import com.cardvalue.sys.mode.Service;
import com.cardvalue.sys.mode.UserService;
import com.cardvalue.sys.newnetwork.Config;
import com.cardvalue.sys.tool.CheckingTools;
import com.cardvalue.sys.tool.ErrorMessage;
import com.cardvalue.sys.tool.Ip;
import com.cardvalue.sys.tool.MD5Util;
import com.cardvalue.sys.tool.MTextWatcher;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends BaseActivity {
    @Bind(R.id.login_button) Button login;  // 登陆按钮
    @Bind(R.id.forget_pwd_button) TextView forgetPwd;	// 忘记密码
    @Bind(R.id.noaccount_button) TextView reg ;  // 注册按钮
    @Bind(R.id.login_mobile) EditText mobile ;  // 手机号输入框
    @Bind(R.id.login_password) EditText password ; // 密码输入框
    @Bind(R.id.iv_right) ImageView close; // 点击了关闭按钮
    @Bind(R.id.textViewtk2) TextView tv;
    @Bind(R.id.ly_checkbox) LinearLayout lyCheckBox;  //授权的那一列
    @Bind(R.id.bindIgreeCheckbox1) CheckBox checkBox;//checkbox
    private  Service.CheckMobile  CheckMobileService;//判断手机是否授权
    private  LoginService LoginService;//登录
    private  UserService  userService;//获取用户
    private Ip  ipService;
    private   Retrofit retrofit;
    private boolean isAuth = true;
    public static  String  loginw;
    private   Realm  realm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        dialog=new ProgressDialog(this,R.style.dialog);
        realm = Realm.getDefaultInstance();
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.getServerIp())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        LoginService=new LoginService(LoginActivity.this);
        userService=new UserService(this);
        ipService=new Ip(this);
        mobile.addTextChangedListener(new MTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if(s.length()>0&&password.length()>0){
                    login.setBackgroundResource(R.drawable.accept_button_style);
                }else{
                    login.setBackgroundResource(R.drawable.disabled_button_style_cc);
                }
                if(s.length()==11){
                    checkMobile();
                }else if(s.length()<11){
                    lyCheckBox.setVisibility(View.GONE);
                }
            }
        });
        password.addTextChangedListener(new MTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if(s.length()>0&&mobile.length()>0){
                    login.setBackgroundResource(R.drawable.accept_button_style);
                }else{
                    login.setBackgroundResource(R.drawable.disabled_button_style_cc);
                }
            }
        });


    }

    @OnClick(R.id.noaccount_button) void clickReg(){//注册的按钮
        startActivity(new Intent(this,BindUserActivity.class));
    }

    @OnClick(R.id.forget_pwd_button) void clickForgetPassword(){//忘记密码的按钮
        startActivity(new Intent(this,ForgetPasswordActivity.class));
    }


    @OnClick (R.id.login_button) void clickLogin(){//点击登录按钮
        ipService.IpService();
        /***判断是否授权 true授权*/
        if(isAuth){
            MessageBox.show(dialog,"登录中","登录中...");
            login();
        }else{
            /***先授权，再登录*/
            try {
                String mobilePhome=mobile.getText().toString().toString().trim();
                if(!CheckingTools.isMobile(mobilePhome)){
                    MessageBox.ToastShow(ErrorMessage.InvalidMobile,this);
                    return;
                }else{
                    String pass=password.getText().toString();
                    long data=System.currentTimeMillis()/1000;
                    String pass1= MD5Util.MD5(MD5Util.MD5(pass)+"cvbaoli"+data)+"|"+data;
                    MessageBox.show(dialog,"创建授权","授权中...");
                    LoginService.attemptCreateAuthorization(mobilePhome, pass1, "ip地址", "推送id", "isLogin", new LoginService.LoginCallback() {
                        @Override
                        public void success() {
                            //登录之后的操作
                            afterLogin();
                            /*userService.getGetUserInfo(LocalCache.getStringLocalData(LoginActivity.this, "objectId"), new UserService.UsesrCallback() {
                                @Override
                                public void success(User user) {
                                   startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                                }

                                @Override
                                public void fail(String msg) {

                                }

                                @Override
                                public void cancelDialog() {

                                }
                            });*/
                        }


                        @Override
                        public void fail(String msg) {

                        }

                        @Override
                        public void cancelDialog() {
                            dialog.dismiss();

                        }
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 登录接口
     */
    private void login(){
        String pass=password.getText().toString();
        long data=System.currentTimeMillis()/1000;
        String pass1= MD5Util.MD5(MD5Util.MD5(pass)+"cvbaoli"+data)+"|"+data;
        LoginService.Login(mobile.getText().toString(), pass1, "推送的id", new LoginService.LoginCallback() {
            @Override
            public void success() {
               // updataMsgUser();
                //登录之后的操作
                afterLogin();
            }


            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {
                dialog.dismiss();

            }
        });
    }


    /**
     * 登录要调用的接口   获取用户    获取最新申请
     * 获取最新授信额度  获取系统消息  正在获取用户消息
     * 正在获取红包  获取商户列表
     */

    public void   afterLogin(){
        userService.getGetUserInfo(LocalCache.getStringLocalData(LoginActivity.this, "objectId"), new UserService.UsesrCallback() {//获取用户
            @Override
            public void success(User user) {
                dialog.cancel();
                Utiltools.printE("tag获取最新的申请user===", JSON.toJSONString(user)+"====");
                LocalCache.saveDataToLocal(LoginActivity.this,"applicationId",user.getApplicationId());//保存applicationId到缓存
                userService.latesApplication(new UserService.GetApplyCallback() {//获取最新的申请
                    @Override
                    public void success(Apply applyInfo) {
                        Utiltools.printE("tag获取最新的申请apply===", JSON.toJSONString(applyInfo)+"====");
                        if(!TextUtils.isEmpty(applyInfo.getCreditId())){//CreditId()不等于空，就直接获取授信
                            userService.getCreditLimitService(applyInfo.getCreditId(), new UserService.GetCreditCallback() {//获取授信
                                @Override
                                public void success(Credit creditLimit) {
                                    startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                                    //updataMsgUser();
                                }

                                @Override
                                public void fail(String msg) {

                                }

                                @Override
                                public void cancelDialog() {

                                }
                            });
                        }else{//  获取系统消息   正在获取用户消息   正在获取红包   获取商户列表   到最后跳转
                            startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                        }





                    }

                    @Override
                    public void fail(String msg) {

                    }

                    @Override
                    public void cancelDialog() {

                    }
                });
            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {

            }
        });
    }


    /**
     * 判断是否授权
     */
    private void checkMobile(){
        CheckMobileService = retrofit.create(Service.CheckMobile.class);
        Call<CheckMobileRegisterAuth> repos = CheckMobileService.attemptCheckMobile(mobile.getText().toString());
        repos.enqueue(new Callback<CheckMobileRegisterAuth>() {
            @Override
            public void onResponse(Call<CheckMobileRegisterAuth> call, Response<CheckMobileRegisterAuth> response) {
                CheckMobileRegisterAuth CheckMobile = response.body();
                String error=CheckMobile.getError()+"";
                if(!error.equals("null")){
                    MessageBox.ToastShow(CheckMobile.getError()+"",LoginActivity.this);
                    return;
                }
                Log.e("CheckMobile",CheckMobile.getHasRegisterAuth()+"|====" + login.getError());
                if(CheckMobile.getHasRegisterAuth().equals("0")){
                    isAuth = false;
                    lyCheckBox.setVisibility(View.VISIBLE);
                }else{
                    isAuth = true;
                    lyCheckBox.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(Call<CheckMobileRegisterAuth> call, Throwable t) {

            }
        });
    }


    //  获取系统消息   正在获取用户消息   正在获取红包   获取商户列表   到最后跳转
    public void updataMsgUser(){
        //获取系统消息
        userService.getMessage("1", new UserService.GetMessageCallback() {
            @Override
            public void success(ArrayList<Message> message) {

            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {

            }
        });
        //正在获取用户消息

        //正在获取红包
        userService.getCoupon();
        //获取商户列表
        userService.getShop();
    }

}
